package com.py.credit.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.entity.HireEntity;
import com.py.credit.service.EasyCreditApplicationService;
import com.py.credit.service.GatewayUserService;
import com.py.credit.service.MsgService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.AccessFlushUtils;
import com.py.credit.utils.IdCardCheckUtil;
import com.py.credit.utils.UuidUtil;
import com.py.credit.utils.ZipUtil;
import com.py.framework.core.controller.BaseController;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.redis.bis.JedisBisManage;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.DateUtils;

import redis.clients.jedis.Jedis;

@RestController
@RequestMapping(value = "/easyCreditLogin")
public class EasyCreditLoginController extends BaseController {

	@Autowired
	private GatewayUserService gatewayUserService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Autowired
	private EasyCreditApplicationService easyCreditApplicationService;
	
	@Autowired
	private MsgService msgService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Value("${aip.idcardcheck.ak}")
	private String ak;

	@Value("${aip.idcardcheck.sk}")
	private String sk;

	/**
	 * 注册用户
	 *
	 * @param username   用户名
	 * @param password   密码
	 * @param sjhm       手机号码
	 * @param ztmc       主体名称
	 * @param bm         编码
	 * @param dzyx       电子邮箱
	 * @param lxr        联系人
	 * @param type       注册类型 C:法人 P：自然人
	 * @param fddbr      法定代表人
	 * @param zjwj       资质文件
	 * @param sfzwjFront 身份证文件正面
	 * @param sfzwjBack  身份证文件反面
	 * @return
	 */
	@RequestMapping(value = "/regist.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addUserInfo(String username, String password, String sjhm, String ztmc, String bm,
			String dzyx, String lxr, String type, MultipartFile sfzwjFront, MultipartFile sfzwjBack) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", username);
		params.put("type", type);

		// 校验账号是否是敏感账户
		if (gatewayUserService.selectUserIsSensitiveAccount(username) > 0) {
			return super.getFailedRestServiceResult("该账号是系统账户,请重新注册");
		}

		// 字段校验
		if (gatewayUserService.getUserByTwoPrincipal(params) != null) {
			return super.getFailedRestServiceResult("该账号已被使用");
		}
		String tybm = (String) xypjRemoteBaseService.checkZmtcIsExist(ztmc, bm, type).getData();

		// 上传文件及大小校验

		if (null == sfzwjFront) {
			return super.getFailedRestServiceResult("请选择身份证正面");
		}

		if (!sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".png")
				&& !sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".jpeg")
				&& !sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
			return super.getFailedRestServiceResult("身份证正面仅支持jpg,jpeg,png格式");
		}

		if (sfzwjFront.getSize() > 5 * 1024 * 1024) {
			return super.getFailedRestServiceResult("身份证正面大小超过5M");
		}

		if (null == sfzwjBack) {
			return super.getFailedRestServiceResult("请选择身份证反面");
		}

		if (!sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".png")
				&& !sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".jpeg")
				&& !sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
			return super.getFailedRestServiceResult("身份证反面仅支持jpg,jpeg,png格式");
		}

		if (sfzwjBack.getSize() > 5 * 1024 * 1024) {
			return super.getFailedRestServiceResult("身份证反面大小超过5M");
		}

		// 拼装成GatewayUserEntity实体类
		GatewayUserEntity entity = new GatewayUserEntity(username, password, sjhm, ztmc, bm, dzyx, lxr, type, null,null,
				tybm);

		if (null != entity) {
			try {
				this.setTimes(entity);

				// 先把文件存到本地,生成一个uuid序列号文件夹
				String dirPath = absolutepath + File.separator + "xypjUser" + File.separator
						+ UuidUtil.getInstance().getUUid();
				entity.setDirPath(dirPath);

				// 存储文件

				gatewayUserService.fileUpload(sfzwjFront, dirPath, "sfzfront_");
				entity.setSfzwj_front("sfzfront_" + sfzwjFront.getOriginalFilename());
				if (IdCardCheckUtil
						.checkIdCard(dirPath + File.separator + "sfzfront_" + sfzwjFront.getOriginalFilename()) != bm) {
					if (null == tybm || tybm.equals("")) {

						entity.setShType("2");
						entity.setShzt("S");
					} else {
						entity.setShType("4");
						entity.setShzt("S");
					}

				} else {
					if (null == tybm || tybm.equals("")) {

						entity.setShType("1");
						entity.setShzt("S");
					} else {
						entity.setShType("3");
						entity.setShzt("T");
					}

				}
				gatewayUserService.fileUpload(sfzwjBack, dirPath, "sfzback_");
				entity.setSfzwj_back("sfzback_" + sfzwjBack.getOriginalFilename());

				entity.setZhzt("J");

				// 默认头像
				String iconPath = dirPath + File.separator + "icon" + File.separator + UuidUtil.getInstance().getUUid();

				gatewayUserService.setDefalutIcon(iconPath, "person.png");

				entity.setIcon(iconPath + File.separator + "icon.png");

				gatewayUserService.addUserInfo(entity);

			} catch (Exception e) {
				result = super.getFailedRestServiceResult("添加失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}

	/**
	 * 定任务更新access-token
	 * 
	 * @return
	 */
	@RequestMapping(value = "/flushAccess.do")
	public RestServiceResult<Object> flushAccess() {
		RestServiceResult<Object> r = new RestServiceResult<>();
		try {
			Jedis jedis = JedisBisManage.getJedis();
			jedis.set("access_token", AccessFlushUtils.getAuth(ak, sk));
			jedis.expire("access_token", 2592000);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("刷新百度权限token调用失败！EasyCreditLoginController#easyCreditLogin/flushAccess.do");
		}
		return r;
	}

	/**
	 * 得到证件照
	 *
	 * @param id
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/getZjPhoto.png")
	public void getZjPhoto(@RequestParam(value = "pathName", defaultValue = "", required = false) String pathName,
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "type", defaultValue = "", required = false) String type, HttpServletResponse response)
			throws IOException {
		String path = "";
		if ("".equals(type)){
			path = easyCreditApplicationService.getPhotoPath(id);
		}else if("ewm".equals(type)){
			path = (msgService.findOneMsg(Long.parseLong(id)).getLinkUrl());
		}else{
			path = easyCreditApplicationService.getPhotoPath(pathName, id, type);
		}
		if (null != path && !"".equals(path)) {
			response.setContentType("image/png");
			response.setCharacterEncoding("UTF-8");
			OutputStream outputSream = response.getOutputStream();

			InputStream fileInputStream = new FileInputStream(path);
			byte[] data = this.toByteArray(fileInputStream);
			fileInputStream.close();

			InputStream in = new ByteArrayInputStream(data);
			in.close();
			int len = 0;

			byte[] buf = new byte[1024];
			while ((len = in.read(buf, 0, 1024)) != -1) {
				outputSream.write(buf, 0, len);
			}

			outputSream.close();
		}
	}

	/**
	 * 压缩包下载
	 * 
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping("/zipDownload.json")
	public RestServiceResult<Object> zipDownload(HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "", required = true) String id) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			Map branch = easyCreditApplicationService.selectOneBranch(id);
			String filePath = String.valueOf(branch.get("path"));
			String[] file = filePath.split(",");
			ZipUtil.zipDownload(file[1], response, file[0]);
			result.setMsg("下载成功！");
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportController#zipDownload", "压缩包下载异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("下载异常，请稍后再试");
			return result;
		}
	}

	private byte[] toByteArray(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}

	/**
	 * 设置当前时间
	 *
	 * @param entity
	 */
	private void setTimes(GatewayUserEntity entity) {
		Timestamp currentTime = new Timestamp(DateUtils.getCurrentDateTime().getTime());
		entity.setCreateTime(currentTime);
		entity.setUpdateTime(currentTime);
		entity.setDelFlag(1);
	}
	
	/**
	 * 忘记密码
	 * 
	 * @param userName
	 * @param password
	 * @param cardPhoto
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value = "/forgetPassword.json", method = RequestMethod.POST)
	public RestServiceResult<Map> forgetPassword(@RequestParam(value = "username", required = true) String userName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "cardphoto", required = true) MultipartFile cardPhoto)
			throws IllegalStateException, IOException {
		RestServiceResult<Map> result = new RestServiceResult<>();
		String dirPath = absolutepath + File.separator + "easyCredit" + File.separator + "forgetPassowrd";
		String cardPath = "";
		if (null != cardPhoto) {
			gatewayUserService.fileUpload(cardPhoto, dirPath, "xyzl_");
			cardPath = dirPath + "/xyzl_" + cardPhoto.getOriginalFilename();
		}
		String cardNumber = IdCardCheckUtil.checkIdCard(cardPath);
		Map<String, Object> user = easyCreditApplicationService.getUser(userName);
		String bm = user.get("bm").toString();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", user.get("id"));
		params.put("newPassword", password);
		if (cardNumber.equals(bm)) {
			gatewayUserService.modifyUserInfo(params);
			result.setMsg("修改成功");
			return result;
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("身份验证失败，请重试");
			return result;
		}
	}

}
